package com.qidian.server.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.qidian.common.Globals;
import com.qidian.common.beans.AccountBean;
import com.qidian.common.beans.GameTypeBean;
import com.qidian.common.beans.MessageBean;
import com.qidian.common.beans.UserBean;
import com.qidian.server.Status;
import com.qidian.util.PageList;

public class GuestServlet extends HttpServlet
{
	private static final long serialVersionUID = 575190150385637446L;
	private static final Logger logger = Logger.getLogger(GuestServlet.class.getName()) ;
//	private static final MServer mserver = MServer.getInstance();
	
	private static String pluginDirPath = null ;
	private static String sampleDirPath = null ;
	
	public void init()
	{
		String absolutePath = this.getServletConfig().getServletContext().getRealPath("/") ;
		pluginDirPath = absolutePath+"/download/plugin";
		File pluginDir = new File(pluginDirPath);
		if(!pluginDir.exists())
			pluginDir.mkdirs();
		sampleDirPath = absolutePath+"/download/sample" ;
		File sampleDir = new File(sampleDirPath);
		if(!sampleDir.exists())
			sampleDir.mkdirs();
		
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException 
	{
		Status status = Status.OK ;
		String actionType = request.getParameter(ServletConstants.arg_action_type) ;
        response.setCharacterEncoding("utf8") ;
		try
		{
			// 检查参数
			if (actionType == null)
			{
		        RequestDispatcher disp = request.getRequestDispatcher("guest_index.html") ;
		        disp.forward(request, response) ;
		        return ;
			}
			else if ("login".equalsIgnoreCase(actionType))
				status = login(request,response) ;
			else if ("getLoginDlg".equalsIgnoreCase(actionType))
				status = getLoginDlg(request,response) ;
			else if ("getDownloadSideBar".equalsIgnoreCase(actionType))
				status = getDownloadSideBar(request,response) ; 
			else if ("getDownloadList".equalsIgnoreCase(actionType))
				status = getDownloadList(request,response) ;
			else if ("download".equalsIgnoreCase(actionType))
				status = download(request,response) ;
			else if ("getGameTypeList".equalsIgnoreCase(actionType))
				status = getGameTypeList(request,response) ;
			else if ("getQuerySingleAccountDlg".equalsIgnoreCase(actionType))
				status = getQuerySingleAccountDlg(request,response) ;
			else if ("getRechargeAccountDlg".equalsIgnoreCase(actionType))
				status = getRechargeAccountDlg(request,response) ;	
			else if ("getMergeAccountDlg".equalsIgnoreCase(actionType))
				status = getMergeAccountDlg(request,response) ;			
			// 在此后的动作需要检查Session变量
			else if (request.getSession().getAttribute(ServletConstants.s_attr_account) == null)
				status = getLoginDlg(request,response) ;
			else if ("getGuestSideBar".equalsIgnoreCase(actionType))
				status = getGuestSideBar(request,response) ;
			else if ("getQueryAnswerRecordDlg".equalsIgnoreCase(actionType))
				status = getQueryAnswerRecordDlg(request,response) ;
			else if ("queryAnswerRecord".equalsIgnoreCase(actionType))
				status = queryAnswerRecord(request,response) ;

			else
				status = Status.INVALID_VALUE ;
		}
		catch(Exception e)
		{
		    e.printStackTrace() ;
		    logger.error(e.getMessage()) ;
		    status = Status.OTHER_ERROR ;
		}
		if (status != Status.OK)
		{

		    response.getWriter().write(status.toString()) ;
		}
	}
	private Status login(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		String account = request.getParameter(ServletConstants.arg_account) ;
		String validCodeAnswer = request.getParameter(ServletConstants.arg_valid_code_answer) ;
//		Status status = Status.OK ;
		String validCode = (String)request.getSession().getAttribute(ServletConstants.s_attr_validate_code) ;
		if(validCodeAnswer == null || validCode == null || account == null )
			return Status.INVALID_ARGUMENT ;
		if(!validCodeAnswer.equalsIgnoreCase(validCode))
			return Status.INVALID_VALIDATE_CODE;

		AccountBean accountBean = Globals.getAccountBuffer().get(account) ;
		if (AccountBean.isValid(accountBean))
		{
			request.getSession().setAttribute(ServletConstants.s_attr_account, account) ;
//			return getGuestSideBar(request,response) ;
			response.getWriter().write(accountBean.toString()) ;
			return Status.OK ;
		}
		else
			return Status.INVALID_VALUE ;
		
	}
	private Status getLoginDlg(HttpServletRequest request,
			HttpServletResponse response) {
		StringBuffer result = new StringBuffer(2048);
		result.append("<form action=\"guest\" method=\"GET\" name=\"loginForm\" id=\"loginForm\">");
       		result.append("<input type=hidden id=actionType name=actionType value=login></input>");
        	result.append("<h3>玩家登录</h3>");
       		result.append("<fieldset>");
       			result.append("<p>子账号&nbsp;/&nbsp;注册码:</p><p><input type=text name=account id=account class=text-long maxlength=48/></input></p>");
	            result.append("<p>验证码:</p><p><input type=\"text\" name=\"validCodeAnswer\" class=\"text-small\" id=\"validCodeAnswer\" value='' maxlength=4></input><img src=\"validatecode\" name=\"validImg\" id=\"validImg\"/><a href=\"javascript:show(document.getElementById('validImg'))\">看不清?</a></p>");
	            result.append("<p><input type=\"button\" class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\"  name=\"submit\" id=\"submit\" value=\"登陆\" onclick=\"guestLogin(); return false;\"/></p>");
       		result.append("</fieldset>");
        result.append("</form>");
        
        try 
        {
        	response.setCharacterEncoding("utf8");
			response.getWriter().write(result.toString()) ;
		} catch (IOException e) {
			e.printStackTrace();
			return Status.OTHER_ERROR;
		}
        
        return Status.OK ;
	}
	private Status getGameTypeList(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		List<GameTypeBean> gameTypeList = Globals.getGameTypeList() ;
		StringBuffer result = new StringBuffer(1024);
//		result.append("<h3>项目类型(充值一律六折优惠，详情请咨询管理员，QQ:272424540)</h3>");
		result.append("<h3>项目类型(没有的项目联系管理员添加，QQ:272424540。<br><span style=\"color:red\">返点率高达30%,首次充值即自动设置。<span></h3>");
		result.append("<table scroll=auto>");
		result.append("<tr align=center>");
//		result.append("<td align=center width=15%><b>序号</b></td>");
		result.append("<td width=15%><b>项目类型</b></td>");
		result.append("<td width=15%><b>项目名</b></td>");
		result.append("<td width=15%><b>题分/题</b></td>");
		result.append("<td width=15%><b>超时时间</b></td>");
//		result.append("<td width=25%><b>答案类型/答案长度</b></td>");
		result.append("<td width=15%><b>答案长度</b></td>");
		result.append("</tr>");
		for(int i = 0 ; i < gameTypeList.size() ; i ++)
		{
			GameTypeBean gameType = gameTypeList.get(i) ;
			result.append("<tr align=center><td>")
				.append(gameType.getGameType()).append("</td><td>")
				.append(gameType.getGameDescription()).append("</td><td>")
				.append(gameType.getPoint()).append("</td><td>")
				.append(gameType.getMinInterval()).append("秒</td><td>")
//				.append(gameType.getAnswerTypeDes()).append("/")
				.append(gameType.getAnswerLen()).append("</td></tr>") ;
//				.append(gameType.getAnswerLen()).append("</td></tr>") ;
		}
		result.append("</table>") ;
		
		response.setCharacterEncoding("utf8") ;
		response.getWriter().write(result.toString()) ;
		return Status.OK;
	}
	
	private Status queryAnswerRecord(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
//		String account = request.getParameter(ServletConstants.arg_account) ;
		String filterRight = request.getParameter(ServletConstants.arg_filter_right);
		String strPageNo = request.getParameter(ServletConstants.arg_page_no) ;
		String strMsgId = request.getParameter(ServletConstants.arg_msg_id);
		String strMinSendTime = request.getParameter(ServletConstants.arg_min_send_time) ;
		String strMaxSendTime = request.getParameter(ServletConstants.arg_max_send_time) ;
		String strGameType = request.getParameter(ServletConstants.arg_game_type) ;
		
		String account = (String)request.getSession().getAttribute(ServletConstants.s_attr_account) ;
//		if(account == null && s_account == null)
		if(account == null)
			return Status.INVALID_ARGUMENT ;
		
//		if (account == null)
//			account = s_account ;
		
		boolean filter = true;
		if("false".equalsIgnoreCase(filterRight))
			filter = false ;
		if (account != null && account.length() > 0 && !AccountBean.isValidFormat(account))
			return Status.INVALID_VALUE ;
		
		
		int gameType = -1 ;
		long msgId = -1 ;
		long minSendTime = -1 ;
		long maxSendTime = -1 ;
		int pageNo = 1 ;
		try
		{
			if (strPageNo != null && strPageNo.length() > 0)
				pageNo = Integer.parseInt(strPageNo) ;
			if (strGameType != null && strGameType.length() > 0)
				gameType = Integer.parseInt(strGameType) ;
			if (strMsgId != null && strMsgId.length() > 0)
				msgId = Long.parseLong(strMsgId) ;
			if (strMinSendTime != null && strMinSendTime.length() > 6)
				minSendTime = Long.parseLong(strMinSendTime) ;
			if (strMaxSendTime != null && strMaxSendTime.length() > 6)
				maxSendTime = Long.parseLong(strMaxSendTime);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return Status.INVALID_VALUE ;
		}
		
		PageList pageList = Globals.getAnswerRecordList(pageNo, account, filter,
				msgId, gameType,  minSendTime, maxSendTime ,null,-1L,-1L);
		if (pageList.getList() == null)
			return Status.OTHER_ERROR ;
		
		StringBuffer result = new StringBuffer(2048) ;

    	result.append("<table cellpadding=\"0\" cellspacing=\"0\">");
			result.append("<tr>");
				result.append("<td>题号</td>");
				result.append("<td>项目类型</td>");
				result.append("<td>发送时间/答题用时</td>");
				result.append("<td>IP</td>");
				result.append("<td>答案</td>");
				result.append("<td>状态</td>");
				result.append("<td class=action>查看</td>");
			result.append("</tr>");
			MessageBean message ;
			Timestamp temp = new Timestamp(System.currentTimeMillis()) ;
			
			for(int i = 0 ; i < pageList.getList().size() ; i ++)
			{
				message = (MessageBean)pageList.getList().get(i) ; 
				result.append("<tr>");
	                result.append("<td>").append(message.getId()).append("</td>");
					result.append("<td>").append(message.getGameType()).append("</td>");
					temp.setTime(message.getReceiveTime()) ;
					result.append("<td>").append(String.format("%02d-%02d %02d:%02d:%02d", temp.getMonth()+1,temp.getDate(),temp.getHours(),temp.getMinutes(),temp.getSeconds())).append("/");
					if(message.getAnswerTime()>0)
						result.append((message.getAnswerTime()-message.getReceiveTime())/1000) ;
					else
						result.append("-</td>");
					
					result.append("<td>").append(message.getIp()).append("</td>");
					result.append("<td>").append(message.getAnswer()==null?"-":message.getAnswer()).append("</td>");
					result.append("<td>").append(message.getMessageStatus()).append("</td>");
					result.append("<td class=action>") ;
					if (message.getContent() == null)
						result.append("-") ;
					else
					{
						String path = Globals.getUploadDirAbsolutePath()+message.getId() ;
						File file = new File(path);
						if(!file.exists())
						{	
							file.createNewFile() ;
							FileOutputStream fos = new FileOutputStream(file);
							fos.write(message.getContent()) ;
							fos.close() ;
						}
						path = Globals.getUploadRelativePath()+message.getId();
						result.append("<a href=\"#\" class=\"view\" onclick=\"onShowImage('").append(path)
						.append("'); return false;\">原图</a>") ;
					}
					result.append("</td>");
	            result.append("</tr>");
			}
        result.append("</table>");
        result.append(pageList.getPageInfo().getHtmlByAction("onQueryAnswerRecord(this);"));
        
    	response.setCharacterEncoding("utf8") ;
		response.getWriter().write(result.toString()) ;

		return Status.OK;		
		
	}
	private Status getQueryAnswerRecordDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		StringBuffer result = new StringBuffer(2048) ;
        result.append("<form >");
        		result.append("<h3>查询条件</h3>");
        					result.append("<div nowrap>");
//        					result.append("<p><label>子账号:</label><input id=account type=text class=textLong maxlength=48 /></p>");
        					result.append("<input id=msgId type=text class=textSmall ></input>") ;
        					result.append("<input id=gameType type=text class=textSmall ></input>") ;
                            result.append("<input id=sendDate name=sendDate type=text class=\"textDate datepicker\" onClick=\"this.datepicker();\" value=").append(new Date(System.currentTimeMillis())).append("></input>从&nbsp;&nbsp;") ;
                            result.append("<input id=minSendTime  type=text class=\"textSmall timepicker\" value=\"00:00:00\"></input>到&nbsp;&nbsp;") ;
                            result.append("<input id=maxSendTime  type=text class=\"textSmall timepicker\" value=\"23:59:59\"></input>") ;
        					result.append("&nbsp;&nbsp;&nbsp;&nbsp;<select id=filterRight class=textMedium>");
        					result.append("<option value=false>全部记录</option>");	
        					result.append("<option value=true>异常记录</option>");
                        	result.append("</select>");
                    		result.append("<input type=submit class=button-submit value=\"查询\" onclick=\"onQueryAnswerRecord();return false;\"/>");
                    		result.append("</div>");
        result.append("</form>") ;
	    
		response.getWriter().write(result.toString()) ;
		
		return Status.OK;
	}
	private Status getRechargeAccountDlg(HttpServletRequest request,
			HttpServletResponse response) {
		StringBuffer result = new StringBuffer(2048) ;
		String s_account = (String)request.getSession().getAttribute(ServletConstants.s_attr_account) ;
        result.append("<form class=\"jNice\">");
        		result.append("<h3>子账号充值</h3>");
        		result.append("<fieldset>");
                        	result.append("<p><label>子账号:</label><input id=account type=\"text\" class=\"text-long\" maxlength=48 value=\"").append(s_account==null?"":s_account).append("\" /></p>");
                        	result.append("<p><label>充值卡号:</label><input id=rechargeCard type=\"text\" class=\"text-long\" maxlength=48/></p>");
                    		result.append("<input type=submit  class=button-submit value=充值 onclick=\"rechargeAccount();return false;\"/>");
               result.append("</fieldset>");
        result.append("</form>") ;
	    try 
	    {
	    	response.setCharacterEncoding("utf8") ;
			response.getWriter().write(result.toString()) ;
		}
	    catch (IOException e) 
		{
			e.printStackTrace();
			return Status.OTHER_ERROR;
		}
		return Status.OK;
	}
	private Status getMergeAccountDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		StringBuffer result = new StringBuffer(2048) ;
		String s_account = (String)request.getSession().getAttribute(ServletConstants.s_attr_account) ;

        result.append("<form class=\"jNice\">");
		result.append("<h3>子账号充值(新购的子账号的点数将合并到原有子账号)</h3>");
		result.append("<fieldset>");
                	result.append("<p><label>原有子账号:</label><input id=accountA type=\"text\" class=\"text-long\" maxlength=48 value=\"").append(s_account==null?"":s_account).append("\" /></p>");
                	result.append("<p><label>新购的子账号:</label><input id=accountB type=\"text\" class=\"text-long\" maxlength=48/></p>");
            		result.append("<input type=\"submit\" class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\"  value=\"充值\" onclick=\"mergeAccount();return false;\"/>");
        result.append("</fieldset>");
        result.append("</form>") ;

		response.getWriter().write(result.toString()) ;

		return Status.OK;
	}	
	private Status getQuerySingleAccountDlg(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String s_account = (String)request.getSession().getAttribute(ServletConstants.s_attr_account) ;
		StringBuffer result = new StringBuffer(2048) ;
		result.append("<form class=\"jNice\">");
        		result.append("<h3>查询条件</h3>");
        		result.append("<fieldset>");
        		result.append("<p><label>子账号:</label><input id=account type=text class=text-long maxlength=48 value=\"").append(s_account==null?"":s_account).append("\" /></p>");
        		result.append("<input type=submit class=\"ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all\" value=查询 onclick=\"onQuerySingleAccount();return false;\"/>");
               result.append("</fieldset>");
        result.append("</form>") ;

		response.getWriter().write(result.toString()) ;
		return Status.OK;
	}
	private Status getGuestSideBar(HttpServletRequest request,
			HttpServletResponse response) throws IOException 
	{
		StringBuffer result = new StringBuffer(1024) ;
		result.append("[") ;
        result.append("{\"id\":\"createAccount\",\"title\":\"账号信息查询\",\"url\":\"guest?actionType=getQuerySingleAccountDlg\"},") ;
        result.append("{\"id\":\"queryAccount\",\"title\":\"答题记录查询\",\"url\":\"guest?actionType=getQueryAnswerRecordDlg\"},") ;
//        result.append("{\"id\":\"userRecharge\",\"title\":\"账号充值\",\"url\":\"guest?actionType=getRechargeAccountDlg\"}") ;
        result.append("{\"id\":\"userRecharge\",\"title\":\"账号充值\",\"url\":\"guest?actionType=getMergeAccountDlg\"}") ;
        result.append("]") ;

		response.getWriter().write(result.toString()) ;
		return Status.OK;
	}
	private Status getDownloadList(HttpServletRequest request,
			HttpServletResponse response) 
	{
		StringBuffer result = new StringBuffer(2048) ;
		String type = request.getParameter(ServletConstants.arg_type) ;
		
		if (type == null)
			return Status.INVALID_ARGUMENT ;
		String dirPath = null ;
		if (type.equalsIgnoreCase("plugin"))
			dirPath = pluginDirPath ;
		else if (type.equalsIgnoreCase("sample"))
			dirPath = sampleDirPath ;
		else 
			return Status.INVALID_VALUE ;
	
		File downloadDir = new File(dirPath) ;
		File[] files = downloadDir.listFiles() ;
		
		result.append("<h3>文件列表</h3>");
    	result.append("<table cellpadding=\"0\" cellspacing=\"0\">");
		if (files != null)
		for(int i = 0 ; i < files.length ; i ++)
		{
			files[i].getName() ;
			result.append("<tr>");
                result.append("<td><a href=\"download/").append(type).append("/").
                	append(files[i].getName()).append("\">")
                	.append(files[i].getName()).append("</a></td>");
            result.append("</tr>");
		}
        result.append("</table>");
		
	    try 
	    {
	    	// 避免盗链
	    	request.getSession().setAttribute(ServletConstants.s_attr_guest, "guest") ;
	    	response.setCharacterEncoding("utf8") ;
			response.getWriter().write(result.toString()) ;
		}
	    catch (IOException e) 
		{
			e.printStackTrace();
			return Status.OTHER_ERROR;
		}
		return Status.OK;
	}


	private Status download(HttpServletRequest request,
			HttpServletResponse response) {
		
		if (request.getSession().getAttribute(ServletConstants.s_attr_guest) == null)
			return Status.LOGIN_FIRST ;
			
		String type = request.getParameter(ServletConstants.arg_type) ;
		String fileName = request.getParameter(ServletConstants.arg_file_name) ;
		if (type == null || fileName == null)
			return Status.INVALID_ARGUMENT ;
		String dirPath = null ;
		if (type.equalsIgnoreCase("plugin"))
			dirPath = pluginDirPath ;
		else if (type.equalsIgnoreCase("sample"))
			dirPath = sampleDirPath ;
		else 
			return Status.INVALID_VALUE ;
	
		File file = new File(dirPath+"/"+fileName) ;
		
	    try 
	    {
	    	response.setCharacterEncoding("utf8");
	    	response.setHeader("Content-Disposition", "attachment;filename="+fileName);
	    	int bufLen = 2048 ;
	    	byte[] buf = new byte[bufLen];
	    	int readLen = 0 ;
	    	FileInputStream fis = new FileInputStream(file) ;
	    	OutputStream os = response.getOutputStream() ;
	    	while((readLen = fis.read(buf)) > 0)
	    		os.write(buf, 0, readLen) ;
	    	fis.close() ;
	    	os.close() ;
		}
	    catch (IOException e) 
		{
			e.printStackTrace();
			return Status.OTHER_ERROR;
		}
		return Status.OK;
	}


	private Status getDownloadSideBar(HttpServletRequest request,
			HttpServletResponse response) 
	{
		StringBuffer result = new StringBuffer(1024) ;
		result.append("[") ;
        result.append("{\"id\":\"downloadPlugin\",\"title\":\"插件下载\",\"url\":\"guest?actionType=getDownloadList&type=plugin\"},") ;
        result.append("{\"id\":\"downloadSamples\",\"title\":\"示例下载\",\"url\":\"guest?actionType=getDownloadList&type=sample\"}") ;
        result.append("]") ;
	    try 
	    {
	    	response.setCharacterEncoding("utf8") ;
			response.getWriter().write(result.toString()) ;
		}
	    catch (IOException e) 
		{
			e.printStackTrace();
			return Status.OTHER_ERROR;
		}
		return Status.OK;
	}	


}
